package cn.larry.tools.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class HTTPClientUtil {
	private static final DefaultHttpClient httpclient = new DefaultHttpClient();
	
	public static String HTTPPost(String url, List<NameValuePair> list) {
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> nvps = list;
		String result = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));

			HttpResponse response = httpclient.execute(httpPost);
			
			result = readAll(response);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		return result;
	}
	
	public static String HTTPGet(String url) {
		HttpGet httpGet = new HttpGet(url);
		String result = null;
		try {
			HttpResponse response = httpclient.execute(httpGet);
			result = readAll(response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpGet.releaseConnection();
		}
		return result;
	}

	private static String parseEncoding(HttpResponse response) {
		String encoding = "GBK";
		Header[] headers = response.getHeaders("Content-type");
		if (headers != null && headers.length > 0) {
			String value = headers[0].getValue();
			int index;
			if (value != null && (index = value.indexOf("charset=")) != -1) {
				String temp = value.substring(index + "charset=".length());
				if (!temp.trim().isEmpty()) {
					encoding = temp.trim();
				}
			}
		}
		return encoding;
	}

	private static String readAll(HttpResponse response) throws IOException {
		if(response==null){
			throw new IOException("no response!");
		}
		String encoding = parseEncoding(response);
		StatusLine statusLine = response.getStatusLine();
		if (statusLine.getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();

			Header tt = entity.getContentEncoding();
			if (tt != null)
				System.out.println(tt.getValue() + " " + tt.getName());

			byte[] b = new byte[1024];
			InputStream in = entity.getContent();
			int len;
			StringBuilder sb = new StringBuilder();
			while ((len = in.read(b)) != -1) {
				sb.append(new String(b, 0, len, encoding));
			}
			return sb.toString();
		} else {
			return null;
		}
	}


}
